/**
 * @author Hesham Massoud
 * @version 1.0
 */

package models;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.*;

import play.data.validation.Required;
import play.db.jpa.Model;

@Entity
public class MergeRequest extends Model {
	@Lob
	public String mergeReport;
	@ManyToOne
	public Idea firstIdea;
	@ManyToOne
	public Idea secondIdea;
	@ManyToMany(mappedBy = "mergeRequestsRecieved")
	public List<User> recievers;
	@ManyToOne
	public User sender;
	public Date date;
	
	

	/**
	 * Constructs a Merge Request by setting the instance variables to the 
	 * parameters given, then calls the method send().
	 * 
	 * @author Hesham Massoud
	 * 
	 * @story C3S41
	 * 
	 * @param mergeReport
	 * 			It is the report given by the user to describe the details of the merge
	 * 			required.
	 * @param firstIdea
	 * 			It is the first idea to be merged.
	 * @param secondIdea
	 * 			It is the second idea to be merged with the first.
	 * @param recievers 
	 * 			List of the users who are going to receive the request.
	 * @param sender
	 * 			User who is going to send the request
	 *  
	 * */
	public MergeRequest(String mergeReport, Idea firstIdea, Idea secondIdea,
			List<User> recievers, User sender) {
		this.mergeReport = mergeReport;
		this.firstIdea = firstIdea;
		this.secondIdea = secondIdea;
		this.recievers = recievers;
		this.sender = sender;
		this.date = new Date();
		this.send();
	}
	/**
	 *  Adds the merge request to the list of merge requests
	 *  received by all the receivers,and adds the merge request to the list of
	 *  merge requests sent by the sender. This method is only called in the constructor.
	 * 
	 * 
	 * @author Hesham Massoud
	 * 
	 * @story C3S41
	 * */
	public void send() {
		for (User reciever : this.recievers) {
			reciever.mergeRequestsRecieved.add(this);
			reciever.save();
		}
		this.firstIdea.asFirstIdeaMerged.add(this);
		this.secondIdea.asSecondIdeaMerged.add(this);
		this.sender.mergeRequestsSent.add(this);
		this.firstIdea.save();
		this.secondIdea.save();
		this.sender.save();
		this.save();
	}
	
	/** 
	 * @author Ahmed Mahmoud
	 * @return
	 */
	public boolean cascadeDelete(){
		firstIdea.asFirstIdeaMerged.remove(this);
		firstIdea.save();
		secondIdea.asSecondIdeaMerged.remove(this);
		secondIdea.save();
		for(User user : recievers){
			user.mergeRequestsRecieved.remove(this);
			user.save();
		}
		sender.sentRequests.remove(this);
		sender.save();
		this.delete();
		return true;
	}

}